package com.learn.flink.learn.test;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

public class WordCountBatch {

    public static void main(String[] args) throws Exception {
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        String input ="C:\\Users\\Administrator\\Desktop\\word.txt";
        DataSource<String> dataSource = env.readTextFile(input);
        FlatMapOperator<String, Tuple2<String, Integer>> wordDealOpt = dataSource.flatMap(new SplitFunc());
        UnsortedGrouping<Tuple2<String, Integer>> wordGroup = wordDealOpt.groupBy(0);
        DataSet<Tuple2<String, Integer>> sum = wordGroup.sum(1);
        sum.writeAsText("C:\\Users\\Administrator\\Desktop\\output");
        env.execute("word Count");
    }

    static class SplitFunc implements FlatMapFunction<String, Tuple2<String , Integer>> {

        @Override
        public void flatMap(String value, Collector<Tuple2<String, Integer>> collector) throws Exception {
            String[] words = value.split(" ");
            for (String word: words){
                Tuple2<String, Integer> wordDeal = new Tuple2<>(word, 1);
                collector.collect(wordDeal);
            }
        }
    }
}
